import {registerAsync} from '../../api/login/login';
import {validatorNull} from '../../utils/utils';
import {HandleDialog} from '@/hooks/useDialog'

interface UseRegisterOptions {
  tip: (any) => void;
  tipTarget?: string | null;
  back?: () => void;
  handleDialog?: HandleDialog;
  dialog?: any;
}

interface Register {
  <T, S, N>(payload: any, rawDate: S, loginBox: N): void
}

// register hooks
const useRegister: (options: UseRegisterOptions) => Register = (options) => {
  const { tip, tipTarget, back, handleDialog, dialog} = options || {}
  return async (payload, rawDate, loginBox) => {
    const {email, password, confirmPwd, username} = payload || {}
    const {errorCode, message} = validatorNull(payload)
    
    if (errorCode == '0000') {
      tip({content: message, to: loginBox, time: 2000})
      // handleDialog({showDialog: true, title: '测试', content: '测试内容'})
      
      return
    }
    if(password !== confirmPwd) {
      throw {
        errorCode: '400',
        message: '两次输入密码不一致'
      }
    }
    try {
      // 发送注册请求
      const result = await registerAsync({email, password, username})
      if(result?.data?.status === 1) {
        for(let key in payload) {
          rawDate[key] = null
        }
        // TODO - 给出弹窗，选择离开还是停留在页面
        tip({content: '用户注册成功', to: loginBox, time: 2000 })
      } else {
        tip({content: '用户注册失败', to: loginBox, time: 2000})
      }
    } catch (error) {
      console.log(error)
    }
  };
}

export default useRegister